package com.cdn.agent;

/**
 * @author CDN
 * @desc
 */

import com.cdn.agent.enums.OrmType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.sql.Connection;
import java.util.Properties;

@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class SqlLogPlugin implements Interceptor {

    static final Log LOG = LogFactory.getLog("org.apache.ibatis.jdbc");

    public SqlLogPlugin() {
        LOG.info("mybatis log plugin init success……");
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long start = System.currentTimeMillis();
        Object returnValue = invocation.proceed();
        long time = System.currentTimeMillis() - start;
        if (mybatisPlus()) {
            IPrintLog.print(invocation, time, OrmType.PLUS);
        }

        if (mybatisFlex()) {
            IPrintLog.print(invocation, time, OrmType.FLEX);
        }
        return returnValue;
    }

    @Autowired
    private ApplicationContext context;

    /**
     * @author 蔡定努
     */
    public boolean mybatisPlus() {
        return context.containsBean("com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration");
    }

    public boolean mybatisFlex() {
        return context.containsBean("com.mybatisflex.spring.boot.MybatisFlexAutoConfiguration");
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties0) {
    }
}
